<template>
  <div class="weather-container">
    <!-- 头部标题 -->
    <div class="header">
      <h1>桂林市及周边城市历史天气数据</h1>
    </div>

    <!-- 查询和统计组合区域 -->
    <div class="query-stats-wrapper">
      <div class="query-stats-container">
        <!-- 查询面板 -->
        <el-card class="query-panel">
          <el-form :inline="true" :model="queryParams" class="query-form">
            <el-form-item label="时间范围">
              <el-select v-model="queryParams.range" placeholder="选择范围" @change="handleRangeChange">
                <el-option label="全部数据" value="all" />
                <el-option label="按年份" value="year" />
                <el-option label="按年月" value="month" />
              </el-select>
            </el-form-item>

            <el-form-item label="年份" v-if="queryParams.range !== 'all'">
              <el-select v-model="queryParams.year" placeholder="选择年份" :loading="yearLoading">
                <el-option v-for="y in availableYears" :key="y" :label="y" :value="y.toString()" />
              </el-select>
            </el-form-item>

            <el-form-item label="月份" v-if="queryParams.range === 'month'">
              <el-select v-model="queryParams.month" placeholder="选择月份">
                <el-option v-for="m in 12" :key="m" :label="`${m}月`" :value="m.toString().padStart(2, '0')" />
              </el-select>
            </el-form-item>

            <el-form-item label="城市">
              <el-select v-model="queryParams.cities" multiple placeholder="选择城市" style="width: 200px">
                <el-option label="桂林" value="guilin" />
                <el-option label="贺州" value="hezhou" />
                <el-option label="柳州" value="liuzhou" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="fetchData" :loading="loading">
                查询
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 统计卡片区域 -->
        <!-- 统计卡片区域 - 修改为水平布局 -->
        <div class="stats-container">
          <el-card v-for="stat in stats" :key="stat.title" shadow="hover" class="stat-card">
            <div class="stat-content horizontal-layout"> <!-- 添加 horizontal-layout 类 -->
              <div class="stat-icon" :style="{ backgroundColor: stat.color }">
                <component :is="stat.icon" />
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-title">{{ stat.title }}</div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card class="data-table">
      <div class="table-header">
        <h3>天气数据记录</h3>
        <div class="table-actions">
          <el-button size="small" @click="exportData" :disabled="!weatherData.length">
            导出数据
          </el-button>
        </div>
      </div>

      <el-table :data="weatherData" border stripe height="500" v-loading="loading" style="width: 100%">
        <el-table-column label="日期" width="120" sortable>
          <template #default="{ row }">
            {{ formatDate(row.record_date) }}
          </template>
        </el-table-column>

        <template v-for="city in activeCities" :key="city">
          <el-table-column :label="cityMap[city] + '最高温(°C)'">
            <template #default="{ row }">
              {{ row[`${city}_max`] }}
            </template>
          </el-table-column>

          <el-table-column :label="cityMap[city] + '最低温(°C)'">
            <template #default="{ row }">
              {{ row[`${city}_min`] }}
            </template>
          </el-table-column>
        </template>

        <el-table-column prop="guilin_prcp" label="桂林降水量(mm)" />
        <el-table-column prop="guilin_wdsp" label="桂林风速(m/s)" />
      </el-table>

      <div class="pagination">
        <el-pagination v-model:current-page="queryParams.page" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" :total="totalCount"
          @size-change="fetchData" @current-change="fetchData" />
      </div>
    </el-card>
  </div>
</template>


<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import {
  Calendar,
  Location,
  Sunny,
  TrendCharts,
  Document
} from '@element-plus/icons-vue';
import { WeatherApiService } from '@/api/weatherApiService';
import { ElMessage } from 'element-plus';
import { format } from 'date-fns'; // 引入日期格式化函数

// 日期格式化函数（YYYY-MM-DD 格式）
const formatDate = (date: string | Date) => {
  if (!date) return '';
  return format(new Date(date), 'yyyy-MM-dd');
};

// 城市映射
// const cityMap = {
//   guilin: '桂林',
//   hezhou: '贺州',
//   liuzhou: '柳州'
// };

const cityMap: { [key: string]: string } = {
  guilin: '桂林',
  hezhou: '贺州',
  liuzhou: '柳州'
};

// 查询参数
const queryParams = ref({
  range: 'all',
  year: '',
  month: '',
  cities: ['guilin'],
  page: 1,
  pageSize: 20
});

// 数据状态
const weatherData = ref<any[]>([]);
const totalCount = ref(0);
const loading = ref(false);
const yearLoading = ref(false);
const availableYears = ref<number[]>([]);

// 统计卡片数据
const stats = computed(() => [
  {
    title: '总记录数',
    value: totalCount.value,
    icon: Document,
    color: '#409EFF'
  },
  {
    title: '数据年份',
    value: availableYears.value.length > 0
      ? `${Math.min(...availableYears.value)}-${Math.max(...availableYears.value)}`
      : '无',
    icon: Calendar,
    color: '#67C23A'
  },
  {
    title: '覆盖城市',
    value: '3个',
    icon: Location,
    color: '#E6A23C'
  },
  // {
  //   title: '今日天气',
  //   value: '晴朗',
  //   icon: Sunny,
  //   color: '#F56C6C'
  // }
]);

// 当前选中的城市
const activeCities = computed(() => {
  return queryParams.value.cities.length > 0
    ? queryParams.value.cities
    : ['guilin'];
});

// 获取年份数据
const fetchYears = async () => {
  try {
    yearLoading.value = true;
    availableYears.value = await WeatherApiService.getAvailableYears();
  } catch (error) {
    console.error('获取年份失败:', error);
  } finally {
    yearLoading.value = false;
  }
};

// 获取天气数据
const fetchData = async () => {
  try {
    loading.value = true;

    const params = {
      page: queryParams.value.page,
      page_size: queryParams.value.pageSize,
      fields: getSelectedFields()
    };

    let response;

    if (queryParams.value.range === 'year' && queryParams.value.year) {
      response = await WeatherApiService.getDataByYear({
        year: queryParams.value.year,
        ...params
      });
    } else if (queryParams.value.range === 'month' && queryParams.value.year && queryParams.value.month) {
      response = await WeatherApiService.getDataByYearMonth({
        year: queryParams.value.year,
        month: queryParams.value.month,
        ...params
      });
    } else {
      response = await WeatherApiService.getAllData(params);
    }

    weatherData.value = response.data;
    totalCount.value = response.pagination.total_count;
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 获取需要查询的字段
const getSelectedFields = () => {
  const baseFields = ['record_date'];
  const cityFields = activeCities.value.flatMap(city => [
    `${city}_max`,
    `${city}_min`
  ]);

  // 桂林额外字段
  if (activeCities.value.includes('guilin')) {
    cityFields.push('guilin_prcp', 'guilin_wdsp');
  }

  return [...baseFields, ...cityFields];
};

// 导出数据
const exportData = () => {
  // 简单实现 - 实际项目中可以使用更完善的导出方案
  const headers = Object.keys(weatherData.value[0]).join(',');
  const rows = weatherData.value.map(item =>
    Object.values(item).map(v => `"${v}"`).join(',')
  );

  const csvContent = [headers, ...rows].join('\n');
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);

  const link = document.createElement('a');
  link.href = url;
  link.download = `weather_data_${new Date().toISOString().slice(0, 10)}.csv`;
  link.click();
};

// 范围变化处理
const handleRangeChange = () => {
  queryParams.value.page = 1;
  fetchData();
};

onMounted(() => {
  fetchYears();
  fetchData();
});
</script>

<style scoped>
.weather-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 15px;
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.header h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

/* 查询和统计容器布局 */
.query-stats-wrapper {
  margin-bottom: 20px;
}

.query-stats-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 查询面板样式 */
.query-panel {
  width: 100%;
}

.query-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.query-form :deep(.el-form-item) {
  margin-bottom: 0;
  min-width: 180px;
}

.query-form :deep(.el-select) {
  width: 100%;
}

/* 统计卡片容器 - 水平排列 */
.stats-container {
  display: flex;
  gap: 12px;
  width: 100%;
  height: 84px; /* 固定高度防止跳动 */
  overflow-x: auto; /* 允许横向滚动 */
  padding-bottom: 5px; /* 为滚动条留空间 */
}

/* 单个统计卡片样式 */
.stat-card {
  flex: 0 0 240px; /* 固定宽度，不伸缩 */
  height: 80px;
  border-radius: 8px;
  transition: all 0.3s ease;
  overflow: hidden;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

/* 卡片内容水平布局 */
.stat-content {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  height: 100%;
  min-width: 240px; /* 确保最小宽度 */
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: white;
  font-size: 20px;
  flex-shrink: 0;
}

.stat-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.stat-title {
  color: #666;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 数据表格区域 */
.data-table {
  margin-top: 20px;
  width: 100%;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-header h3 {
  margin: 0;
  font-size: 16px;
}

.data-table :deep(.el-table) {
  width: 100%;
}

.data-table :deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: bold;
}

.data-table :deep(.el-table td),
.data-table :deep(.el-table th) {
  padding: 10px 0;
}

.data-table :deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 10px;
  line-height: 1.5;
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (min-width: 1200px) {
  .stat-card {
    max-width: calc(25% - 9px);
  }
}

/* @media (max-width: 1199px) and (min-width: 992px) {
  .stat-card {
    max-width: calc(33.33% - 8px);
  }
}

@media (max-width: 991px) and (min-width: 768px) {
  .stat-card {
    max-width: calc(50% - 6px);
  }
} */

/* 移除响应式设计中的百分比宽度限制 */
@media (max-width: 767px) {
  .stat-card {
    min-width: 240px; /* 保持相同宽度 */
    flex: 0 0 240px;
  }
}

@media (max-width: 767px) {
  .query-form {
    flex-direction: column;
  }

  .query-form :deep(.el-form-item) {
    width: 100%;
    min-width: auto;
  }

  .stat-card {
    min-width: 100%;
  }

  .stat-content {
    padding: 10px 12px;
  }

  .stat-icon {
    width: 36px;
    height: 36px;
    font-size: 18px;
  }
}

@media (max-width: 480px) {
  .weather-container {
    padding: 10px;
  }

  .stat-icon {
    width: 32px;
    height: 32px;
    font-size: 16px;
    margin-right: 8px;
  }

  .stat-value {
    font-size: 14px;
  }

  .stat-title {
    font-size: 11px;
  }
}
</style>